﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using GLIMS.DBUtility;
using System.Xml.Linq;
using System.Data.SqlClient;
using GLIMS.Common;
using System.ServiceModel.Channels;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;

namespace GLIMS.Common.GWF
{
    public class Operation
    {
        public static XElement GetOperation(int operationCode, string nodeCode_From)
        {
            XElement xe = new XElement("gwf_Operation", new XElement("NodeCode_From", nodeCode_From), new XElement("OperationCode", operationCode));

            var row = GWF.DsWorkFlow.Tables["gwf_Operation"].Rows.OfType<DataRow>().FirstOrDefault(x => x["OperationCode"].ToString() == operationCode.ToString() && x["NodeCode_From"].ToString() == nodeCode_From);
            if (row == null)
            {
                throw new Exception("提供的操作编码和节点来源没有找到匹配的行");
            }
            xe.Add(new XElement("OperationName", row["OperationName"]));
            
            xe.Add(new XElement("WhereText", row["WhereText"]));

            string nodeCode_To = row["NodeCode_To"].ToString();
            string nodeName_To = Node.GetNodeName(nodeCode_To);
            xe.Add(new XElement("NodeCode_To", nodeCode_To), new XElement("NodeName_To", nodeName_To));

            string nodeName_From = Node.GetNodeName(nodeCode_From);
            xe.Add(new XElement("NodeName_From", nodeName_From));

            string flowCode = row["FlowCode"].ToString();
            string flowName = Flow.GetFlowName(flowCode);
            xe.Add(new XElement("FlowCode", flowCode), new XElement("FlowName", flowName));

            xe.Add(new XElement("AfterDone", row["AfterDone"] == DBNull.Value ? "" : row["AfterDone"]));
            xe.Add(new XElement("AfterCancelled", row["AfterCancelled"] == DBNull.Value ? "" : row["AfterCancelled"]));
            xe.Add(new XElement("BeforeCancelling", row["BeforeCancelling"] == DBNull.Value ? "" : row["BeforeCancelling"]));

            return xe;
        }


        /// <summary>
        /// 获取指定界面的所有操作信息
        /// </summary>
        /// <param name="formCode"></param>
        /// <returns></returns>
        public static XElement[] GetOperation(int formCode) 
        {
            return GWF.DsWorkFlow.Tables["gwf_Operation"].Rows.OfType<DataRow>().Where(x => x["FormCode"].ToString() == formCode.ToString())
                .Select(x => new XElement(x.Table.TableName
                    , new XElement("OperationCode", x["NodeCode_From"])
                    , new XElement("NodeCode_From", x["NodeCode_From"])
                    , new XElement("NodeCode_To", x["NodeCode_To"])
                    )).ToArray();
        
        }
    }
}